package com.droid.mvvmlib.widget.listener;

import android.view.View;

import com.droid.mvvmlib.log.Logcat;

/**
 * 防止多次点击
 */

public abstract class OnNoRepeatClickListener implements View.OnClickListener {

    private static final String TAG = "OnNoRepeatClickListener";

    public static final int MIN_CLICK_DELAY_TIME_DEFAULT = 500;
    private final long interval;

    /**
     * 上次点击按钮的时间
     **/
    private long lastClickTime = 0;

    /**
     * 全局上次点击按钮的时间
     */
    private static long globalLastClickTime;
    private boolean globalInterval;

    public OnNoRepeatClickListener(long interval) {
        this.interval = interval;
    }

    public OnNoRepeatClickListener() {
        this(MIN_CLICK_DELAY_TIME_DEFAULT);
    }

    /**
     * 全局范围的多个按钮，在一定时间范围内不允许重复点击
     *
     * @param globalScape 是否支持应用全局范围内只点击一次
     */
    public OnNoRepeatClickListener(boolean globalScape, long interval) {
        this(interval);
        this.globalInterval = globalScape;
    }

    public abstract void onNoRepeatClick(View v);

    @Override
    public void onClick(View v) {
        long lastClickTime = this.globalInterval ? globalLastClickTime : this.lastClickTime;
        long curClickTime = System.currentTimeMillis();
        if (Math.abs(curClickTime - lastClickTime) > interval) {
            if (this.globalInterval) {
                updateGlobalLastClickTime(curClickTime);
            } else {
                this.lastClickTime = curClickTime;
            }
            onNoRepeatClick(v);
        } else {
            Logcat.d(TAG, "You are click too fast!");
        }
    }

    private static void updateGlobalLastClickTime(long clickTime) {
        globalLastClickTime = clickTime;
    }
}
